package com.vip.vcsp.multiprocess;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;

import java.lang.reflect.Method;
import java.util.HashMap;

public class MultiProcessManager {

    public static int MSG_INVOKE_MSG = 1;

    private static HashMap<String, Object> rpcMap = new HashMap();

    private MultiProcessManager() {
        throw new UnsupportedOperationException("unsupport init MultiProcessManager");
    }

    public static void register(Object obj) {
        rpcMap.put(obj.getClass().getName(), obj);
    }

    public static void register(String name,Object obj) {
        rpcMap.put(name, obj);
    }

    public static Object getService(String serviceName) {
        return rpcMap.get(serviceName);
    }

    public static void connect(Context context, IConnectListener rpcListener) {
        MultiProcessHelper helper = new MultiProcessHelper(context);
        helper.startAndBindService();
        helper.setIConnectListener(rpcListener);
    }

    public static <T> void invoke(final MultiProcessHelper helper,Class rpcServiceCls, String methodName, IInvokeListener<T> invokeListener, Object... args) {

        try {
            Method[] methods = rpcServiceCls.getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (methods[i].getName().equals(methodName)) {
                    Method method = methods[i];
                    helper.addRpcInvokeListener(method.getName(),invokeListener);
                    Messenger messenger = helper.getServerMessenger();
                    Message message = Message.obtain();
                    message.what = MSG_INVOKE_MSG;
                    message.replyTo = helper.getClientMessenger();
                    Bundle bundle = new Bundle();
                    bundle.putString("serviceName", rpcServiceCls.getName());
                    bundle.putString("methodName", method.getName());
                    bundle.putSerializable("parameterTypes", method.getParameterTypes());
                    bundle.putSerializable("arguments", args);
                    message.setData(bundle);
                    messenger.send(message);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
